//
//  PopoverTableVC.m
//  stone-story
//
//  Created by liu dodo on 12-9-25.
//  Copyright (c) 2012年 liu dodo. All rights reserved.
//

#import "PopoverTableVC.h"

@interface PopoverTableVC ()

@end

@implementation PopoverTableVC
@synthesize resultArray=_resultArray;
@synthesize parentcategroyID=_parentcategroyID;
@synthesize delegate = _delegate;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        
        [self.navigationItem setTitle:NSLocalizedString(@"产品选择",@"")];
        UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
        temporaryBarButtonItem.title = @"返回";
        temporaryBarButtonItem.target = self;
        self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController.navigationBar setTintColor:[UIColor orangeColor]];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    _resultArray = [[NSMutableArray alloc] init];
    
    
    [self FMDB_init];
    [self queryTable:_parentcategroyID];

    
}

- (void)viewWillAppear:(BOOL)animated {
    
    CGSize size = CGSizeMake(250,400); // size of view in popover
    self.contentSizeForViewInPopover = size;
    
    [super viewWillAppear:animated];
    
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return [_resultArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    // Configure the cell...
    NSDictionary *cell_text = [_resultArray objectAtIndex:indexPath.row];
    cell.textLabel.text=[cell_text  objectForKey:@"categroy_name"];
    
    return cell;
}



#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self FMDB_init];
    // Navigation logic may go here. Create and push another view controller.
     NSDictionary *resulte_text = [_resultArray objectAtIndex:indexPath.row];
    //查询是否有子类别
    FMResultSet *rs =[db executeQuery:@"SELECT count(*) FROM tb_categroy WHERE parentcategory_id = ?",[resulte_text  objectForKey:@"categroy_id"]];
    while ([rs next])
    {
        int totalCount = [rs intForColumnIndex:0];
        //判断查询子类别的条数 如果有子类别 则进入
        if (totalCount)
        {
            PopoverTableVC *detailViewController = [[PopoverTableVC alloc] initWithNibName:nil bundle:nil];
             detailViewController.parentcategroyID=[resulte_text  objectForKey:@"categroy_id"];
            detailViewController.navigationItem.Title=[resulte_text  objectForKey:@"categroy_name"];
            
            //这一步是把代理继续传下去
            detailViewController.delegate= self.delegate;
            
            [self.navigationController pushViewController:detailViewController animated:YES];
        }
        else // 如果没有子类别 实现代理方法
        {
            if ([_delegate respondsToSelector:@selector(PopoverTableVCDoneAction:)])
            {
                [_delegate PopoverTableVCDoneAction:[resulte_text  objectForKey:@"categroy_id"]];
        
            }
            
        }
   }
    [rs close];
    [db close];
}




#pragma mark - 数据库操作
//创建或打开数据库
- (void)FMDB_init//1
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    
    //dbPath： 数据库路径，在Document中。
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"db_stoneStory.db"];
    
    //创建数据库实例 db  这里说明下:如果路径中不存在"Test.db"的文件,sqlite会自动创建"Test.db"
    db= [FMDatabase databaseWithPath:dbPath];
    if (![db open])
    {
        NSLog(@"Could not open db.");
        return ;
    }
    else
    {
        NSLog(@"open db. success!");
    }
    
    
    
}



//查询
- (void)queryTable:(NSString *)parentID
{
    //返回数据库中第一条满足条件的结果
    //   NSString *aa=[db stringForQuery:@"SELECT Name FROM User WHERE Age = ?",@"20"];
    
    //返回全部查询结果
    NSLog(@"%@,",parentID);
  
    FMResultSet *rs =[db executeQuery:@"SELECT * FROM tb_categroy WHERE parentcategory_id = ? ORDER BY categroy_id ASC",parentID];
    while ([rs next])
    {
            NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
           // NSLog(@"\n categroy_id:%@ \n categro_image:%@ \n  parentcategory_id:%@ \n note:%@ \n ",[rs stringForColumn:@"categroy_id"],[rs stringForColumn:@"categroy_name"],[rs stringForColumn:@"parentcategory_id"],[rs stringForColumn:@"note"]);
            [item setObject:[rs stringForColumn:@"categroy_id"] forKey:@"categroy_id"];
            [item setObject:[rs stringForColumn:@"categroy_name"] forKey:@"categroy_name"];
            [item setObject:[rs stringForColumn:@"parentcategory_id"] forKey:@"parentcategory_id"];
            [item setObject:[rs stringForColumn:@"note"] forKey:@"note"];
            
            [ _resultArray addObject:item];
    }

    [rs close];
    [db close];
}







@end
